// src/components/sidebar/ButtonsGroup.tsx

import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { FaUserCircle, FaCog, FaPowerOff, FaUserPlus } from 'react-icons/fa';
import { PiUserListFill } from 'react-icons/pi';
import UserList from '@/components/popups/adminEditPermission/UserList';
import Profile from '@/components/popups/userActions/Profile';
import Settings from '@/components/popups/userActions/Settings';
import Logout from '@/components/popups/userActions/Logout';
import { useUserStore } from '@/store/userStore';
import React from 'react';

const ButtonsGroup = ({ collapsed = false, mobile = false }: { collapsed?: boolean; mobile?: boolean }) => {
  const navigate = useNavigate();
  const { user, setUser, clearUser } = useUserStore();
  const [showUserList, setShowUserList] = useState(false);
  const [showProfile, setShowProfile] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [showLogout, setShowLogout] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token && window.location.pathname !== '/login') {
      localStorage.removeItem('token');
      localStorage.removeItem('theme');
      localStorage.removeItem('dashboardTab');
      localStorage.removeItem('sidebar_collapsed');
      clearUser();
      navigate('/login');
    }
  }, [navigate, clearUser]);

  useEffect(() => {
    const handleUserUpdated = (e: CustomEvent) => {
      const updated = e.detail;
      setUser((prev) => ({
        ...prev,
        ...updated,
      }));
    };
    window.addEventListener('userUpdated', handleUserUpdated as EventListener);
    return () => {
      window.removeEventListener('userUpdated', handleUserUpdated as EventListener);
    };
  }, [setUser]);

  const buttons = [
    ...(user.role === 'Admin'
      ? [
        {
          key: 'userList',
          icon: <PiUserListFill />, label: 'User Management', onClick: () => setShowUserList(true),
        },
        {
          key: 'createAccount',
          icon: <FaUserPlus />, label: 'Create Account', onClick: () => navigate('/create-account'),
        },
      ]
      : []),
    {
      key: 'profile',
      icon: <FaUserCircle />, label: 'Profile', onClick: () => setShowProfile(true),
    },
    {
      key: 'settings',
      icon: <FaCog />, label: 'Settings', onClick: () => setShowSettings(true),
    },
    {
      key: 'logout',
      icon: <FaPowerOff />, label: 'Logout', onClick: () => setShowLogout(true),
    },
  ].filter((b): b is { key: string; icon: React.ReactElement; label: string; onClick: () => void } => b !== null);

  return (
    <div className={`relative w-full ${mobile ? 'flex flex-row justify-around items-center py-1 border-t border-gray-200 dark:border-slate-800 bg-white dark:bg-slate-900' : 'flex flex-col items-center'} transition-all duration-300`}>
      <div className={`${mobile ? 'flex flex-row w-full justify-around gap-0.5' : 'flex flex-col w-full gap-2 py-4 border-b border-gray-100 dark:border-slate-800'} items-center px-3`}>
        {buttons.map((btn) => (
          <div
            key={btn.key}
            className={`relative group w-full`}
          >
            <button
              className={`flex items-center w-full rounded-xl transition-all duration-200 ease-in-out
                ${mobile ? 'justify-center text-xl shadow-sm py-1.5 px-1.5' : 'gap-4 px-4 py-3 text-lg font-medium'}
                ${btn.key === 'logout'
                  ? 'text-red-500 hover:bg-red-50 dark:hover:bg-red-900 hover:text-red-700 dark:hover:text-red-300'
                  : 'text-gray-700 dark:text-gray-200 hover:bg-blue-50 dark:hover:bg-slate-700 hover:text-blue-700 dark:hover:text-cyan-300'}
                focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-1
                border border-transparent hover:border-blue-200 dark:hover:border-cyan-700 shadow-sm group
              `}
              onClick={btn.onClick}
              aria-label={btn.label}
              tabIndex={0}
              type="button"
            >
              <span className={`transition-all duration-200 ${mobile ? 'text-xl' : 'text-2xl'} ${btn.key === 'logout' ? 'text-red-400 group-hover:text-red-600 dark:group-hover:text-red-300' : 'text-blue-400 dark:text-cyan-400 group-hover:text-blue-600 dark:group-hover:text-cyan-300'}`}>{btn.icon}</span>
              {!collapsed && !mobile && (
                <span className={`ml-1 whitespace-nowrap text-base transition-all duration-200 ${btn.key === 'logout' ? 'text-red-500 group-hover:text-red-700 dark:group-hover:text-red-300' : 'text-gray-800 dark:text-gray-200 group-hover:text-blue-700 dark:group-hover:text-cyan-300'}`}>
                  {btn.label}
                </span>
              )}
            </button>
          </div>
        ))}
      </div>
      {showUserList && <UserList onClose={() => setShowUserList(false)} />}
      {showProfile && <Profile onClose={() => setShowProfile(false)} />}
      {showSettings && (
        <Settings
          onClose={() => setShowSettings(false)}
          onUpdateUser={(updated) =>
            setUser((prev) => ({
              ...prev,
              ...(updated.first_name !== undefined && { firstName: updated.first_name }),
              ...(updated.last_name !== undefined && { lastName: updated.last_name }),
              ...(updated.email !== undefined && { email: updated.email }),
            }))
          }
        />
      )}
      {showLogout && (
        <Logout
          onConfirm={() => {
            localStorage.removeItem('token');
            localStorage.removeItem('theme');
            localStorage.removeItem('dashboardTab');
            localStorage.removeItem('sidebar_collapsed');
            clearUser();
            navigate('/login');
            setShowLogout(false);
          }}
          onCancel={() => setShowLogout(false)}
        />
      )}
    </div>
  );
};

export default ButtonsGroup;